<?php

namespace App\Services;

class XingKongPay
{
    public static $uri = 'https://t-wapi.bhecard.com:8443';

    public static $is_debug = true;
    //公钥
    public static $public_key = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCAqRw0nZ1rGTpAeKupP7coS+en6BveJL4aFVt9men4Zzkpuv/IeK6YJ2yk4m8ppZ7TLW4t5WsPEhYOnUfMtjhW4nuQfjgU54juJ1KMHYiX9gaaO+z80ZnaiKD2YsZMFiE9dlTeBlkRL5xXbHa+JonHfVKXMr13oI8oZNKdpnvknQIDAQAB";
    public static $private_key = "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAOSxfpYzsR5pKg0lpDb8rwhmJuaN06l+o9wf5FvKFoGCGt0yMmv/OUqsiFzuatZ7VV2hx/WavOVVubMr6YXD8/GINStC/6Hj7ih30XDjQLM1TRmBfhux+FO3LEYUULKbp/LZz+tXDU6QN6Hvw3CGNRhwdAV5Sq1d0REg7tbPuCZpAgMBAAECgYBigmpqvN2AogAxJZO08+dZkNcU3ObdzeU7fqlZOJW1N5vmyCacCpZdKjCbB0ASH5JIANYnX34as3CIU1QGAMBk63Rm7LYF7mPu3r+qYUhwt60FTynxktkKgvtr2slDNc+oF4noAKvzd3W752RWn/lp9rGvhkk8gljaBVa0A+4A+QJBAP6R2b7dDdmICLJFJV8EdKJjThndSQymS4MLT2p3ZdT2ULhMtLjbOy0FeQaBFEkF6cy8TquIvO76qwlNCPlO5qcCQQDl+mz7s7Pd6SaMcuAMPDnuCNqVZNspseP3WmnB3q/Bt3Ad+dTtoopVYgvrIAb+VxVkZ804k3c192wl9BilVTxvAkEA4I4jdztjRim7EhXwezpg8AWNFT+femsOXRATA6VCzHJijdAL8qxgLLyRH22pSSjQLetFsgYyMtQnH1M2wUQaLQJBAKNDNa02NKF8C+a3AoENHF70oCBgegnOhLSr1dpQuVr/W7OcEWIl+qiEs0tW8EANGF2wJwtb/Mwt+vOypvBwYzcCQQCff7Cv+JHXx+voggV+lJqkBpFGjIV2axQ97n4JrBxwok7y42KEhMrKqVRAzXp7iGSxXfq7AkL0JSU7gSz+dg/3";
    public static function pay($order){

        $post_data = [
            'orgId'=>'ORG000000004784',
            'orgMercode'=>'531000023046245',
            'orgTermno'=>'33859055',
            'orgTrace'=>'ORG0'.'4784'.date('YmdHis').rand(100000,999999),
            'signType'=>'RSA2',
            'appendData'=>[
                "invoiceSt"=> false,
                "terminalinfo"=>[
                    "terminalIp"=>"127.0.0.1",
                ]
            ],
            "data"=>[
                "infoAttach"=>"订单描述",
                "orderInfo"=>"订单标题",
                "orgBackUrl"=>route('notice_pay'),
                "splitSettleFlag"=>"0",
                "timeoutMinutes"=>300,
                "tradeAmt"=>1,
                "tradeCode"=>"WAC2B"
            ]
        ];
        $sign = self::buildSign($post_data['data']);
        $post_data['sign'] = $sign;


        $req_url = self::$uri.'/standard/native';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $req_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        $post_data = json_encode($post_data,JSON_UNESCAPED_UNICODE);
        if(self::$is_debug){
            echo '请求地址:';
            echo $req_url;
            echo '请求报文:';
            echo $post_data;
        }
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); // 设置HTTP头部信息


        $out = curl_exec($ch);
        curl_close($ch);
        $outArr = json_decode($out,true);
        var_dump($outArr);
    }

    /**
     *    微信支付
     * @return void
     */
    public static function wechat_pay($order){

    }

    /**
     * 获取openID
     * @return void
     */
    public static function wechat_openid($auth_code){
        $post_data = [
            'orgId'=>'ORG000000004784',
            'orgMercode'=>'531000023046245',
            'orgTermno'=>'33859055',
            'orgTrace'=>'ORG0'.'4784'.date('YmdHis').rand(100000,999999),
            'signType'=>'RSA2',
            'data'=>[
                'authCode'=>$auth_code
            ]
            ];
        $sign = self::buildSign($post_data['data']);
        $post_data['sign'] = $sign;


        $req_url = self::$uri.'/standard/getOpenId';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $req_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        $post_data = json_encode($post_data,JSON_UNESCAPED_UNICODE);
        if(self::$is_debug){
            echo '请求地址:';
            echo $req_url;
            echo '请求报文:';
            echo $post_data;
        }
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); // 设置HTTP头部信息


        $out = curl_exec($ch);
        curl_close($ch);
        $outArr = json_decode($out,true);
        var_dump($outArr);
    }

    /**
     * 生成签名
     * @param $params
     * @return string
     */
    public static function buildSign($params){
        ksort($params);
        $params_data = http_build_query($params);
        $params_data = urldecode($params_data);
        //echo '拼接请求参数：'.$params_data;

        return self::createSha256WithRSA($params_data, self::$private_key);
    }

    /**
     * 加密
     * @param $params
     * @return void
     */
    public static function createSha256WithRSA($content, $privateKey){
        $privateKey = "-----BEGIN RSA PRIVATE KEY-----\n" .
            wordwrap($privateKey, 64, "\n", true) .
            "\n-----END RSA PRIVATE KEY-----";

        $key = openssl_get_privatekey($privateKey);
        openssl_sign($content, $signature, $key, "SHA256");
        openssl_free_key($key);
        $sign = base64_encode($signature);
        //echo '加密后的sign:'.$sign;
        return $sign;
    }

    /**
     * 揭秘
     * @param $params
     * @return void
     */
    public static function verifySha256WithRSA($content, $sign, $publicKey)
    {
        $publicKey = "-----BEGIN PUBLIC KEY-----\n" .
            wordwrap($publicKey, 64, "\n", true) .
            "\n-----END PUBLIC KEY-----";

        $key = openssl_get_publickey($publicKey);
        $ok = openssl_verify($content,base64_decode($sign), $key, 'SHA256');
        openssl_free_key($key);
        return $ok;
    }
}
